package com.roam.cofig;

import io.micrometer.common.util.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListToVarcharTypeHandler implements TypeHandler<List<String>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        if(parameter==null){
            ps.setNull(i, Types.VARCHAR);
        }else{
            StringBuffer sb = new StringBuffer();
            for(int j = 0;j<parameter.size();j++){
                if(j==parameter.size()-1){
                    sb.append(parameter.get(j));
                }else{
                    sb.append(parameter.get(j)).append(",");
                }
            }
            ps.setString(i,sb.toString());
        }
    }

    @Override
    public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
        String resultString = rs.getString(columnName);
        if(StringUtils.isNotEmpty(resultString)){
            return Arrays.asList(resultString.split(","));
        }
        return new ArrayList<>();
    }

    @Override
    public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String resultString = rs.getString(columnIndex);
        if(StringUtils.isNotEmpty(resultString)){
            return Arrays.asList(resultString.split(","));
        }
        return new ArrayList<>();
    }

    @Override
    public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String resultString = cs.getString(columnIndex);
        if(StringUtils.isNotEmpty(resultString)){
            return Arrays.asList(resultString.split(","));
        }
        return new ArrayList<>();
    }
}
